package cc.bluemc.modules.generateCode.entity;

import cc.bluemc.platform.utils.FreemarkerUtil;
import freemarker.template.Template;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Generate {
	
	private Log log = LogFactory.getLog(this.getClass());
    private JdbcTemplate jdbcTemplate;
    /**
     * 数据库名
     */
    private String SCHEMA_NAME;

    public Generate(JdbcTemplate jdbcTemplate,String dbName) {
    	this.jdbcTemplate =jdbcTemplate;
    	this.SCHEMA_NAME=dbName;
	}
    public List<TableBean> getTable(String tableName) {
    	log.info("查询数据库……");
    	jdbcTemplate.execute("USE information_schema");
    	StringBuffer sql = new StringBuffer("select * from tables where table_schema = ?");
    	List params= new ArrayList();
    	params.add(SCHEMA_NAME);
    	if(StringUtils.isNotBlank(tableName)){
    		sql.append(" AND Table_name = ?");
    		params.add(tableName);
    	}
        List<TableBean> tableBeanList = jdbcTemplate.query(sql.toString(), params.toArray(),
                new RowMapper() {
                    @Override
                    public TableBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                        String tableName = rs.getString("table_name");
                        String tableNameTrimed = tableName;
                        //表名生成规则
                        if (tableName.startsWith("t_")) {
                            tableNameTrimed = tableName.substring(2);
                        }
                        
                        TableBean bean = new TableBean();
                        bean.setTableName(tableName);
                        bean.setTableNameNoDash(delDash(tableNameTrimed));
                        bean.setTableNameCapitalized(StringUtils.capitalize(bean.getTableNameNoDash()));
                        bean.setTableComment(rs.getString("table_comment"));
                        log.info("查询到表："+bean.toString());
                        return bean;
                    }
                });

        for (TableBean tableBean : tableBeanList) {
            tableBean.setColumnBeanList(getColumns(tableBean.getTableName(), tableBean));
        }
        return tableBeanList;
    }
    private List<ColumnBean> getColumns(String tableName, final TableBean tableBean) {
        return jdbcTemplate.query("select * from COLUMNS where table_schema = ? and table_name = ?",
                new Object[]{SCHEMA_NAME, tableName},
                new RowMapper() {
                    @Override
                    public ColumnBean mapRow(ResultSet rs, int rowNum) throws SQLException {
                        ColumnBean bean = new ColumnBean();
                        String columnName = rs.getString("column_name");
                        bean.setColumnName(columnName);
                        bean.setColumnNameNoDash(delDash(columnName));
                        bean.setColumnNameCapitalized(StringUtils.capitalize(bean.getColumnNameNoDash()));
                        bean.setColumnComment(rs.getString("column_comment"));

                        String columnType = rs.getString("column_type").toLowerCase();
                         if (columnType.startsWith("int")) {
                            if(columnType.contains("unsigned")) {
                                bean.setColumnType("Long");
                                bean.setColumnTypeRsGetter("getLong");
                            } else {
                                bean.setColumnType("Integer");
                                bean.setColumnTypeRsGetter("getInt");
                            }
                        } else if (columnType.startsWith("bigint")) {
                            bean.setColumnType("Long");
                            bean.setColumnTypeRsGetter("getLong");
                        } else if (("timestamp").equals(columnType)||("datetime").equals(columnType)) {
                            bean.setColumnType("Date");
                            bean.setColumnTypeRsGetter("getDate");
                            tableBean.setHasDateColumn(true);
                        } else if (columnType.startsWith("float")) {
                            bean.setColumnType("Float");
                            bean.setColumnTypeRsGetter("getFloat");
                        } else if (columnType.startsWith("double")) {
                            bean.setColumnType("Double");
                            bean.setColumnTypeRsGetter("getDouble");
                        } else if (columnType.startsWith("decimal")) {
                            bean.setColumnType("BigDecimal");
                            bean.setColumnTypeRsGetter("getBigDecimal");
                            tableBean.setHasBigDecimal(true);
                        } else {
                        	 bean.setColumnType("String");
                             bean.setColumnTypeRsGetter("getString");
                        }

                        return bean;
                    }
                });
    }
    private  String delDash(String str) {
        String lowerCaseStr = str.toLowerCase();
        String[] noDashArray = StringUtils.split(lowerCaseStr, '_');
        StringBuilder noDash = new StringBuilder(noDashArray[0]);
        for (int i = 1; i < noDashArray.length; i++) {
            noDash.append(StringUtils.capitalize(noDashArray[i]));
        }
        return noDash.toString();
    }

   public void execute(String dbName,String tableName){
	   
   }
   public void execute(String dbName){
	   
   }
   public static void main(String[] args) throws IOException {
	   System.out.println("开始生成代码");
	   
       String OUTPUT_PATH = "d:/generate/"; //输出路径绝对地址
       String JDK_VERSION = "com/ristone/platform/generate/jdk6";  //模板路径
       String PACKAGE_BASE = "com.ristone.platform.adminUser"; //package
       String TABLE_NAME=""; //表名
	    String SCHEMA_NAME="test"; //数据库名
	    
	    
	   JdbcTemplate jdbcTemplate = (JdbcTemplate) new ClassPathXmlApplicationContext("applicationContext.xml").getBean("jdbcTemplate");
	   Generate generate = new Generate(jdbcTemplate,SCHEMA_NAME); 

	   File outputPath = new File(OUTPUT_PATH);
       if (!outputPath.isDirectory()) {
           FileUtils.forceMkdir(outputPath);
       }
       String outputDirs = OUTPUT_PATH + "/" + StringUtils.replace(PACKAGE_BASE, ".", "/");
       List<TableBean> tableBeanList = generate.getTable(TABLE_NAME);
       for (TableBean tableBean : tableBeanList) {
           Map<String, Object> varMap = new HashMap<String, Object>();
           varMap.put("tableBean", tableBean);
           varMap.put("schemaName", SCHEMA_NAME);
           varMap.put("packageBase", PACKAGE_BASE);
           Template modelTemplate = FreemarkerUtil.getTemplate(JDK_VERSION + "Temp/model.ftl");
           FreemarkerUtil.outputProcessResult(outputDirs+ tableBean.getTableNameNoDash() + "/entity/" + tableBean.getTableNameCapitalized() + ".java", modelTemplate, varMap);

          /* Template daoTemplate = FreemarkerUtil.getTemplate(JDK_VERSION + "Temp/dao.ftl");
           FreemarkerUtil.outputProcessResult(outputDirs+ tableBean.getTableNameNoDash() + "/dao/" + tableBean.getTableNameCapitalized() + "DAO.java", daoTemplate, varMap);

           Template daoimplTemplate = FreemarkerUtil.getTemplate(JDK_VERSION + "Temp/daoimpl.ftl");
           FreemarkerUtil.outputProcessResult(outputDirs+ tableBean.getTableNameNoDash() + "/dao/" + tableBean.getTableNameCapitalized() + "DAOImpl.java", daoimplTemplate, varMap);

           Template serviceTemplate = FreemarkerUtil.getTemplate(JDK_VERSION + "Temp/service.ftl");
           FreemarkerUtil.outputProcessResult(outputDirs+ tableBean.getTableNameNoDash() + "/service/" + tableBean.getTableNameCapitalized() + "Service.java", serviceTemplate, varMap);

           Template serviceimplTemplate = FreemarkerUtil.getTemplate(JDK_VERSION + "Temp/serviceimpl.ftl");
          FreemarkerUtil.outputProcessResult(outputDirs+ tableBean.getTableNameNoDash() + "/service/" + tableBean.getTableNameCapitalized() + "ServiceImpl.java", serviceimplTemplate, varMap);
           */
       }
       System.out.println("结束生成代码");
   }
}
